﻿@section scripts {
<script src="https://cdn.jsdelivr.net/npm/vue@3.3.4/dist/vue.global.min.js"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<link rel="stylesheet" href="https://unpkg.com/element-plus/dist/index.css">
<script src="https://unpkg.com/element-plus/dist/index.full.min.js"></script>
<script src="https://unpkg.com/element-plus/dist/locale/zh-cn.min.js"></script>
<script>
    const { createApp, ref, reactive, onMounted } = Vue;
    const { ElMessage, ElMessageBox } = ElementPlus;

    const app = createApp({
      setup() {
        const formData = reactive({
          fsk_id: null, // 主键（修改时由 URL 传递）
          first_kind_id: null, // I级机构编号（下拉选 value）
          first_kind_name: '', // I级机构名称（下拉选 label）
          second_kind_id: '', // II级机构编号
          second_kind_name: '', // II级机构名称（必填）
          second_salary_id: '', // 薪酬责任人编号（必填）
          second_sale_id: '' // 销售责任人编号（必填）
        });

        const firstKindOptions = ref([
          { value: null, label: '请选择I级机构名称...' },
          { value: '02', label: 'Ⅰ级结构' },
          { value: '01', label: '集团' },
          { value: '03', label: '总部' }
        ]);

        const rules = reactive({
          first_kind_name: [{ required: true, message: '请选择I级机构名称', trigger: 'change' }],
          second_kind_name: [{ required: true, message: 'II级机构名称不能为空', trigger: 'blur' }],
          second_salary_id: [{ required: true, message: '薪酬发放责任人编号不能为空', trigger: 'blur' }],
          second_sale_id: [{ required: true, message: '销售责任人编号不能为空', trigger: 'blur' }]
        });

        const formRef = ref(null); // 表单引用

        // 处理I级机构选择
        const handleFirstKindChange = (value) => {
          const selectedItem = firstKindOptions.value.find(item => item.value === value);
          formData.first_kind_id = value;
          formData.first_kind_name = selectedItem?.label || '';
        };

        // 初始化数据（修改时加载）
        const initFormData = () => {
          const urlParams = new URLSearchParams(window.location.search);
          const fsk_id = urlParams.get('fsk_id');
          const encodedData = urlParams.get('data');

          if (fsk_id) {
            formData.fsk_id = fsk_id; // 设置主键
          }

          if (encodedData) {
            try {
              const data = JSON.parse(decodeURIComponent(encodedData));
              Object.assign(formData, data); // 合并数据
              // 触发下拉选更新
              if (data.first_kind_id) handleFirstKindChange(data.first_kind_id);
            } catch (error) {
              console.error('数据解析失败:', error);
              ElMessage.error('加载数据失败，请重试');
            }
          }
        };

        // 提交表单（新增/修改）
        const handleSubmit = async () => {
          // 触发表单验证
          if (formRef.value && !await formRef.value.validate()) return;

          try {
            const isUpdate = !!formData.fsk_id;
            const baseUrl = '@Url.Action("secondUpdate", "config")'; // 假设后端路由支持 /config/secondUpdate?fsk_id=xxx
            const url = isUpdate
              ? `${baseUrl}?fsk_id=${formData.fsk_id}` // 修改时传递主键
              : baseUrl; // 新增时无需主键

            const response = await axios({
              method: isUpdate ? 'put' : 'post',
              url: url,
              data: formData, // 直接传递响应式对象（无需 .value）
              headers: { 'Content-Type': 'application/json' }
            });

            if (response.data.success) {
              ElMessage.success(isUpdate ? '修改成功' : '新增成功');
              window.location.href = '@Url.Action("config_file_second_kind", "config")';
            } else {
              ElMessageBox.alert(response.data.message, { type: 'error' });
            }
          } catch (error) {
            console.error('请求失败:', error.response?.data || error);
            ElMessage.error(isUpdate ? '修改失败' : '新增失败，请检查网络或数据');
          }
        };

        // 页面加载初始化
        onMounted(initFormData);

        return {
          formData,
          firstKindOptions,
          rules,
          formRef,
          handleFirstKindChange,
          handleSubmit,
          handleBack: () => window.history.back() // 简化返回逻辑
        };
      }
    });

    app.use(ElementPlus, { locale: ElementPlusLocaleZhCn });
    app.mount('#vue-app');
</script>
}

<div id="vue-app">
    <div class="config-file-first-kind">
        <div class="breadcrumb">
            <font color="black">
                您正在做的业务是：人力资源--客户化设置--人力资源档案管理设置--I级机构设置--I级机构管理
            </font>
        </div>

        <el-form :model="formData" :rules="rules" ref="formRef" label-width="180px" class="el-form-demo">
            <el-form-item label="I级机构名称" prop="first_kind_name">
                <el-select v-model="formData.first_kind_name"
                           placeholder="请选择I级机构名称"
                v-on:change ="handleFirstKindChange">
                    <el-option v-for="item in firstKindOptions"
                               :key="item.value"
                               :label="item.label"
                               :value="item.value"></el-option>
                </el-select>
            </el-form-item>

            <el-form-item label="II级机构编号" prop="second_kind_id">
                <el-input v-model="formData.second_kind_id"></el-input>
            </el-form-item>

            <el-form-item label="II级机构名称" prop="second_kind_name">
                <el-input v-model="formData.second_kind_name"></el-input>
            </el-form-item>

            <el-form-item label="薪酬发放责任人编号" prop="second_salary_id">
                <el-input v-model="formData.second_salary_id"></el-input>
            </el-form-item>

            <el-form-item label="销售责任人编号" prop="second_sale_id">
                <el-input v-model="formData.second_sale_id"></el-input>
            </el-form-item>

            <el-form-item>
                <el-button type="primary" v-on:click="handleSubmit">
                    {{ formData.fsk_id ? '保存修改' : '新增机构' }}
                </el-button>
                <el-button v-on:click="handleBack">返回</el-button>
            </el-form-item>
        </el-form>
    </div>
</div>